package cn.wgx.commons.config.web;

import cn.wgx.commons.interceptor.FileInterceptor;
import cn.wgx.commons.interceptor.RequestTimeLimit;
import cn.wgx.commons.listener.ConfigListener;
import cn.wgx.modules.sys.interceptor.UserHandlerInterceptor;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.LinkedList;
import java.util.List;

/**
 * web 配置类
 *
 * @author fengshuonan
 * @date 2016年11月12日 下午5:03:32
 */
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Value("${allPathPre}")
    private String allPathPre;
    @Value("${maxUploadSize}")
    private Long maxUploadSize ;
    @Value("${maxInMemorySize}")
    private Integer maxInMemorySize ;
    @Value("${maxUploadSizePerFile}")
    private Long maxUploadSizePerFile ;
    @Value("${upload.folder}")
    public String uploadFolder;

    @Autowired
    private FileInterceptor fileInterceptor;
    /**
     * 静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //swagger
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

//        registry.addResourceHandler("/**").addResourceLocations("file:" + uploadFolder);
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //文件上传过滤器
        registry.addInterceptor(fileInterceptor)
                .addPathPatterns(allPathPre + "fileupload/**")
                .addPathPatterns(allPathPre + "resfile/upload**");

        //用户对数据的所有修改进行记录,包括 增删改
        registry.addInterceptor(new UserHandlerInterceptor())
                .addPathPatterns(allPathPre + "**/**insert**")
                .addPathPatterns(allPathPre + "**/**add**")
                .addPathPatterns(allPathPre + "**/**update**")
                .addPathPatterns(allPathPre + "**/**del**")
                .addPathPatterns(allPathPre + "**/**upload**")
//                .addPathPatterns(allPathPre + "**/**download**")
//                .excludePathPatterns(allPathPre + "**/**list**")
//                .excludePathPatterns(allPathPre + "**/**get**")
        ;
        //请求过快过滤器,1秒以上
        registry.addInterceptor(new RequestTimeLimit())
        .addPathPatterns(allPathPre + "**");
    }


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        LinkedList<MediaType> linkedList = new LinkedList<>();
        linkedList.add(MediaType.APPLICATION_JSON);
        linkedList.add(MediaType.TEXT_HTML);
        fastConverter.setSupportedMediaTypes(linkedList);
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,        // 是否输出值为null的字段,默认为false,我们将它打开
                SerializerFeature.WriteNullListAsEmpty,     // 将Collection类型字段的字段空值输出为[]
                SerializerFeature.WriteNullStringAsEmpty,   // 将字符串类型字段的空值输出为空字符串
                SerializerFeature.WriteNullNumberAsZero,    // 将数值类型字段的空值输出为0
                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.DisableCircularReferenceDetect);    // 禁用循环引用
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);

        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
//        stringHttpMessageConverter.setDefaultCharset("");
        LinkedList<MediaType> linkedList2 = new LinkedList<>();
        linkedList2.add(MediaType.APPLICATION_JSON);
        stringHttpMessageConverter.setSupportedMediaTypes(linkedList2);
        converters.add(stringHttpMessageConverter);
    }


    @Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        commonsMultipartResolver.setDefaultEncoding("utf-8");
        commonsMultipartResolver.setMaxUploadSize(maxUploadSize);
        commonsMultipartResolver.setMaxInMemorySize(maxInMemorySize);
        commonsMultipartResolver.setMaxUploadSizePerFile(maxUploadSizePerFile);
        return commonsMultipartResolver;
    }

    /**
     * RequestContextListener注册
     */
    @Bean
    public ServletListenerRegistrationBean<RequestContextListener> requestContextListenerRegistration() {
        return new ServletListenerRegistrationBean<>(new RequestContextListener());
    }

    /**
     * ConfigListener注册
     */
    @Bean
    public ServletListenerRegistrationBean<ConfigListener> configListenerRegistration() {
        return new ServletListenerRegistrationBean<>(new ConfigListener());
    }



}
